package com.daona.application.service;

import com.daona.model.template.BaseModel;
import com.lowagie.text.pdf.BaseFont;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.OutputStream;

@Service
@RequiredArgsConstructor
public class PdfService {

    private final TemplateEngine templateEngine;

    /**
     * 生成HTML内容
     * @return 渲染后的HTML字符串
     */
    private String generateHtmlContent(String templateName, Object data) {
        Context context = new Context();
        context.setVariable(templateName, data);
        return templateEngine.process(templateName, context);
    }

    public void htmlToPdf(OutputStream outputStream, BaseModel data) throws Exception {
        // 创建ITextRenderer实例
        ITextRenderer renderer = new ITextRenderer();

        // 设置字体路径，使用 classpath 加载字体
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("static/font/SimSun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        String htmlContent = generateHtmlContent(data.getTemplateName(), data);
        renderer.setDocumentFromString(htmlContent);
        renderer.layout();

        // 输出PDF到响应输出流
        renderer.createPDF(outputStream);
        outputStream.close();
        outputStream.flush();
    }

}
